<template>
    <div class="TicketLogin">
        <img v-if="isLoginError" class="TicketLogin-loading" src="@/image/loading.gif"></img>
        <img v-else class="TicketLogin-loading" src="@/image/failed.png"></img>
        <div class="TicketLogin-text">{{titleVal}}</div>
    </div>
</template>

<script>
    import {ACCESS_TOKEN} from '@/store/mutation-types'
    import {mapActions,mapState, mapMutations} from 'vuex'

    export default {
        name:'TicketLogin',
        data() {
            return {
                titleVal:this.i18n('tips.loging','正在进行登录，请稍候...'),
                isLoginError: false,
                //跳转URL
                redirect:"",
                //默认logo
                loginPageLogoUrl: process.env.BASE_URL + 'image/log.png',
                //密码模式
                passwordmode:"default",
                state: {
                    loginBtn: false,
                    loginType: 0,
                },
            }
        },
        created() {
            let route=this.$route;
            //记录跳转回日志。
            if(route.query.redirect){
                this.redirect= route.query.redirect;
            }
            this.ticketLogin();
        },

        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "viewsUser", key);
            },
            ...mapActions({
                AuthorizeTicketLogin: 'user/AuthorizeTicketLogin',
                Logout: 'user/Logout',
                setLogined: 'appSetting/setLogined',
            }),
            ...mapMutations('appSetting', ['setNavigation', 'setActiveKey','setAppKey','setBreadList','setPasswordmode','setSiteName']),
            // name 是你要获取的那个参数的字段 比如 code=我是谁 name 就是 code
            getQueryString(name) {
                var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
                var r = decodeURIComponent(window.location.search).substr(1).match(reg)
                if (r !== null) return r[2]
                return null
            },
            //集成ticket登录
            ticketLogin() {
                var basePath = process.env.VUE_APP_ADMIN_FRONT;
                //储存 portalUrl 用在jpaas-portal门户 里面用;
                window.localStorage.setItem('portalUrl', basePath);
                if (this.getQueryString('token') != null) {
                    var token = decodeURIComponent(this.getQueryString('token'));
                    Vue.ls.set(ACCESS_TOKEN, token, 12 * 60 * 60 * 1000)
                    this.$store.commit('SET_TOKEN', token)

                    this.$router.push({name: 'index'}, () => {
                        this.$notification.success({
                            message: this.i18n('tips.welcome','欢迎'),
                            description: `${timeFix()}，` + this.i18n('tips.welcomeBack','欢迎回来!')
                        })
                    });

                    this.isLoginError = false
                }
                /**
                 * cas检测是否存在ticket
                 */
                var ticket = this.getDecodeURIQueryString('ticket');
                //登录成功后回调
                if (ticket) {
                    this.logTicketLogin(ticket);
                    return;
                }else{
                    this.isLoginError = true;
                    this.titleVal=this.i18n('tips.empty','url没有出入ticket参数或者ticket参数值位空!');
                }
            },
            logTicketLogin(ticket) {
                const {
                    state,
                    AuthorizeTicketLogin
                } = this;
                state.loginBtn = true;
                const loginParams = {
                    ticket:ticket
                };
                AuthorizeTicketLogin(loginParams)
                    .then((res) => this.loginSuccess(res))
                    .catch(err => this.requestFailed(err))
                    .finally(() => {
                        state.loginBtn = false
                    });
            },
            getDecodeURIQueryString (variable) {
                var newUrl =decodeURIComponent(window.location.search);
                //alert("--newUrl="+newUrl);
                if(newUrl.indexOf("/?")>-1){
                    var urlList = newUrl.split("/?");
                    newUrl= urlList[1];
                }
                var param =newUrl;
                if(param.indexOf("&")>-1){
                    var list = param.split("&");
                    for(var i=0;i<list.length;i++){
                        var obj = list[i];
                        if(obj.indexOf(variable)>-1){
                            var returnList =obj.split("=");
                            return returnList[1];
                        }
                    }
                }else{
                    if(param.indexOf(variable)>-1){
                        var returnList =param.split("=");
                        return returnList[1];
                    }
                }
                return null;
            },
            //登录成功处理
            loginSuccess(res) {
                if (res.code === 200) {
                    //存在需要跳转的URL,则跳转到指定的URL
                    if(this.redirect){
                        this.$router.push({ path: this.redirect });
                    }
                    else{
                        this.$router.push({ name: 'home-index' }, () => {
                            this.$notification.success({
                                message: this.i18n('tips.welcome','欢迎'),
                                description: `${timeFix()}，` + this.i18n('tips.welcomeBack','欢迎回来!')
                            })
                        })
                    }
                    this.isLoginError = false
                } else {
                    this.requestFailed(res)
                }
            },
            //登录失败处理
            requestFailed(err) {
                this.isLoginError = true;
                this.titleVal=this.i18n('tips.parameter','根据ticket参数登录失败!');
            },
        }
    }
</script>
<style lang="less" scoped>
.TicketLogin{
    display: flex;
    flex-direction: column;
    background: white;
    position: fixed;
    top: 0;
    left: 0px;
    bottom: 0px;
    right: 0px;
    z-index: 9999;
    transform: inherit;
}
.TicketLogin-loading{
    width: 700px;
    margin: auto;
    margin-top: 100px;
}
.TicketLogin-text{
    text-align: center;
    color: #333333;
    font-size: 20px;
    flex: 1;
    margin-top: -195px;
}
</style>
